package kibahed.university.effizientealgorithmen.interfaces;

import java.util.HashMap;
import java.util.Map;

import kibahed.university.effizientealgorithmen.abstractclasses.AVertex;
import kibahed.university.effizientealgorithmen.standardclasses.EdgeWithCosts;

public abstract class AAlgorithm implements IAlgorithm {

	

	protected IGraph graph;
	private StringBuilder builder = new StringBuilder();
	
	protected IEdge[] resultEdges=null; 
	
	@Override
	public void setGraph(IGraph graph) {
		this.graph = graph;
	}
	
	public void clearConsole(){
		builder = new StringBuilder();
	}
	
	protected void addConsoleText(String string){
		builder.append(string).append("\n");
	}
	
	public String getConsoleText(){
		return builder.toString();
	}
	
	@Override
	public IEdge[] getResult() {
		return resultEdges;
	}

	@Override
	public void setResult(IEdge[] result) {
		resultEdges=result;
		
	}
	
	protected boolean checkResult() {
		Map<AVertex,Integer> map = new HashMap<AVertex,Integer>();
		System.out.println("Number of result edges = "+resultEdges.length);
		for(IEdge e : resultEdges) {
			AVertex startVertex = (AVertex)e.getStartVertex();
			AVertex endVertex = (AVertex)e.getEndVertex();
			if(map.containsKey(startVertex)) {
				map.put(startVertex, map.get(startVertex)+1);
			} else {
				map.put(startVertex, 1);
			}
			if(map.containsKey(endVertex)) {
				map.put(endVertex, map.get(endVertex)+1);
			} else {
				map.put(endVertex, 1);
			}
		}
		
		for(IVertex v : map.keySet()) {
			if(map.get(v)!=2) {
				return false;
			}
		} 
		return true;
	}
	
	protected int getIntegerTourLength() {
		int length = 0;
		if(resultEdges.length > 0) {
			for(IEdge e : resultEdges) {
				if(e instanceof EdgeWithCosts) {
					length += Math.round(((EdgeWithCosts)e).getCost());
				}else{
					return -1;
				}
			}
		}
		return length;
	}
}
